/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Ancestor.Dao.js
 * @path:   js-src/Ancestor/
 * @desc:   负责本模块的远程调用的静态对象
 * @author: jiegang@qiyi.com
 * @date:   2015-01-12
 */
qui(
    function(require, exports, module) {

        Ancestor.Dao = (function() {
            var config = Ancestor.Config;

            var ajax = function(options, authPath) {
                if (authPath)
                    $.ajax($.extend(options, {
                        beforeSend: function(request) {
                            var authBase = Ancestor.Util.getAuth(authPath);
                            request.setRequestHeader('Sign', authBase.sign);
                            request.setRequestHeader("Time", authBase.clientTime);
                            request.setRequestHeader("From", authBase.from);
                            request.setRequestHeader("UserName", (auth.baseInfo.authInfo==null) ? "" : escape(auth.baseInfo.authInfo.userName).toLocaleLowerCase().replace(/%u/gi, '\\u'));
                        }
                    }));
                else
                    $.ajax(options);
            };

            // 获取配频道配置数据
            var getType = function(data, callback) {
                var options = {
                    url: config.CONFIGS_API.url,
                    dataType: 'json',
                    data: data,
                    method: 'get',

                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/configs");

            };

            var getSuggestData = function(url, data, callback) {

                var request = {};
                request.url = url;
                request.type = 'get';

                if (data.needCookie)
                    request.needCookie = true;

                request.params = data;

                data = {
                    request: JSON.stringify(request)
                };

                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, '/redirect');
            };

            var getQipuDataById = function(item, callback) {
                var url = Ancestor.Config.QIPU_URL.replace("${QIPUID}", item.qipuId);

                var request = {};
                request.url = url;
                request.type = 'get';

                var data = {
                    request: JSON.stringify(request)
                };

                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    method: 'post',
                    data: data,
                    success: function(data) {
                        callback.call(this, data, item);
                    },
                    error: function(data) {
                        callback.call(this, data, item);
                    }
                };

                ajax(options, '/redirect');
            };

            // 获取分类
            var getuniversalCodeData = function(url, data, callback) {

                var options = {
                    url: url,
                    dataType: 'json',
                    data: data,
                    method: 'post',
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, url.split('api')[1]);
            };

            // XMLHttp Request
            var _getXHR = function() {
                return new XMLHttpRequest() || new ActiveXObject('Msxml2.XMLHTTP') || new ActiveXObject('Microsoft.XMLHTTP');
            };

            var qichuanUploadFile = function(data, handler) {
                var self = this;
                var xhr = _getXHR();
                var precent = 0;
                xhr.open('POST', data.url, true);
                // xhr.setRequestHeader('Content-Type', 'multipart/form-data');
                for (var key in data.headers) {
                    xhr.setRequestHeader(key, data.headers[key]);
                }

                xhr.upload.onprogress = function(e) {
                    var data = xhr.responseText ? JSON.parse(xhr.responseText) : null;
                    if (e.lengthComputable) {
                        precent = (e.loaded / e.total) * 100;
                        if (handler.onProgress) {
                            handler.onProgress.apply(self, [precent, data]);
                        }
                    }
                };

                xhr.onreadystatechange = function() {
                    var data = xhr.responseText ? JSON.parse(xhr.responseText) : null;
                    if (xhr.readyState == 4) {
                        var stat = xhr.status;
                        if ((stat >= 200 && stat < 300) || stat == 304 || stat == 1223 || stat === 0) {
                            if (handler.onFinish) {
                                handler.onFinish.call(self, data);
                            }
                        } else {
                            if (handler.onFail) {
                                handler.onFail.call(self, data);
                            }
                        }
                    }
                };

                var formData = new FormData();
                formData.append('businessType', data.headers['businessType']);
                formData.append('fileid', data.headers['file_id']);
                formData.append('imagefile', data.file);

                // xhr.send(data.file || null);
                xhr.send(formData);


                return xhr;
            };


            var qichuanRequestFile = function(options, callback) {
                options = options || {};
                var headers = options.headers || {};

                var options = {
                    url: options.url + '?t=' + new Date().getTime(),
                    // url: options.url,
                    dataType: 'json',
                    // data: data,
                    headers: headers,
                    method: 'get',
                    success: function(data) {
                        if (data && data.code == 'A00000') {
                            callback.call(this, data);
                        } else {
                            console.log('get access fail.');
                            callback.call(this, data);
                        }
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, false);

            };

            var platSettings = function(options, callback) {
                var options = {
                    url: '/api/channel/getPlatSettings',
                    dataType: 'json',
                    data: options,
                    method: 'post',

                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/channel/getPlatSettings");
            };

            var redirectRequest = function(options, callback) {
                var options = {
                    url: '/api/redirect',
                    dataType: 'json',
                    data: options,
                    method: 'post',
                    beforeSend: function(request) {
                        var auth = Ancestor.Util.getAuth('/redirect');
                        request.setRequestHeader('Sign', auth.sign);
                        request.setRequestHeader("Time", auth.clientTime);
                        request.setRequestHeader("From", auth.from);
                    },
                    success: function(data) {
                        callback.call(this, data);
                    },
                    error: function(data) {
                        callback.call(this, data);
                    }
                };

                ajax(options, "/redirect");
            };

            return {
                getType: getType,
                qichuanRequestFile: qichuanRequestFile,
                qichuanUploadFile: qichuanUploadFile,
                getSuggestData: getSuggestData,
                platSettings: platSettings,
                getuniversalCodeData: getuniversalCodeData,
                getQipuDataById: getQipuDataById,
                redirectRequest: redirectRequest,
                ajax: ajax
            };
        })();
    }
);